package com.xuecheng.content.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CourseBaseDto;
import com.xuecheng.commons.model.dto.CourseDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.model.vo.CourseBaseVo;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.config.MinioProperties;
import com.xuecheng.content.config.MinioTemplate;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exception.BusinessException;
import io.minio.MinioClient;
import io.minio.errors.MinioException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-03
 */
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {

//    //分页+条件查询
//    @Override
//    public ResponseResult<CourseBaseVo> findByPage(PageRequest pageRequest, CourseDto dto) {
//        // 1.构建分页
//        Page<CourseBase> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
//        // 2.构建条件
//        LambdaQueryWrapper<CourseBase> qw = new LambdaQueryWrapper<>();
//        // 2-1 课程名称
//        qw.like(StrUtil.isNotEmpty(dto.getCourseName()), CourseBase::getName, dto.getCourseName());
//        // 2-2 课程状态
//        qw.eq(StrUtil.isNotEmpty(dto.getAuditStatus()), CourseBase::getAuditStatus, dto.getAuditStatus());
//        // 2-3 课程类型
//        qw.eq(StrUtil.isNotEmpty(dto.getTeachmode()), CourseBase::getTeachmode, dto.getTeachmode());
//        // 3.分页查询
//        page = this.page(page, qw);
//        // 4.转vo
//        List<CourseBase> courseBaseList = page.getRecords();
//        List<CourseBaseVo> voList = new ArrayList<>();
//        for (CourseBase courseBase : courseBaseList) {
//            CourseBaseVo vo = BeanHelper.copyProperties(courseBase, CourseBaseVo.class);
//            voList.add(vo);
//        }
//        // 5.返回结果
//        return PageResponseResult.okResult(page.getTotal(),voList);
//    }


    @Override
    public ResponseResult<CourseBaseVo> findByPage(PageRequest pageRequest, CourseDto dto) {
        // 1.构建分页
        Page<CourseBase> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
        // 2.构建条件（链式编程）
        page = this.lambdaQuery()
                .like(StrUtil.isNotEmpty(dto.getCourseName()), CourseBase::getName, dto.getCourseName())//课程名称
                .eq(StrUtil.isNotEmpty(dto.getAuditStatus()), CourseBase::getAuditStatus, dto.getAuditStatus())//课程状态
                .eq(StrUtil.isNotEmpty(dto.getTeachmode()), CourseBase::getTeachmode, dto.getTeachmode())//课程类型
//                .eq(CourseBase::getCompanyId, AuthInfoHolder.getCompanyId())//多租户的数据隔离
                .page(page);//分页查询
        // 4.转vo
        List<CourseBaseVo> voList = BeanHelper.copyWithCollection(page.getRecords(), CourseBaseVo.class);
        // 5.返回结果
        return PageResponseResult.okResult(page.getTotal(), voList);
    }

    @Autowired
    private TeachplanService teachplanService;
    // 课程新增
    @Override
    public ResponseResult<Map> saveCourseBase(CourseBaseDto dto) {
        // 1.校验前端参数 （新增：id和价格不能校验）
        if (!StrUtil.isAllNotEmpty(dto.getName(), dto.getTags(), dto.getMt(), dto.getSt(), dto.getGrade())) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        // 2.dto转entity
        CourseBase courseBase = BeanHelper.copyProperties(dto, CourseBase.class);
        // 3.补全课程信息
        courseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);// 未提交课程状态
        courseBase.setPlanNum(0);// 课程小节数量
        courseBase.setCreateDate(new Date());// 课程新增时间
        // 4.保存数据库
        boolean save = this.save(courseBase);
        if (save == false) {
            throw new BusinessException(ErrorCode.ADDEERROR);
        }
        // 5.初始化一级大纲 （预留）
        Teachplan teachplan = new Teachplan();
        teachplan.setPname(courseBase.getName());// 一级大纲名称（课程信息名称）
        teachplan.setParentid(0L);// 一级大纲父节点id为0
        teachplan.setGrade(1); // 一级
        teachplan.setDescription(courseBase.getDescription());// 课程介绍
        teachplan.setCourseId(courseBase.getId());// 课程id
        teachplan.setCreateDate(new Date()); // 创建时间
        teachplanService.save(teachplan);

        // 6.返回课程id
        Map map = new HashMap();
        map.put("courseBaseId", courseBase.getId());
        return ResponseResult.okResult(map);
    }

    // 课程修改
    @Override
    public ResponseResult<Map> updateCourseBase(CourseBaseDto dto) {
        // 1.校验前端参数 （修改：价格不能校验）
        if (!StrUtil.isAllNotEmpty(dto.getName(), dto.getTags(), dto.getMt(), dto.getSt(), dto.getGrade())) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        if (ObjectUtil.isEmpty(dto.getId())) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        // 2.校验课程状态
        // 2-1 查询数据库
        CourseBase oldCourseBase = this.getById(dto.getId());
        // 2-2 判断状态
        if (StrUtil.equals(oldCourseBase.getAuditStatus(), CourseConstants.AUDIT_PASTED_STATUS)) {
            //已发布（上架）课程，不能改
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        // 3.dto转实体
        CourseBase newCourseBase = BeanHelper.copyProperties(dto, CourseBase.class);
        newCourseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);//重置课程状态
        // 4.更新数据库
        boolean isSuccess = this.updateById(newCourseBase);
        if (isSuccess == false) {
            throw new BusinessException(ErrorCode.UPDATEEERROR);
        }
        // 5.更新课程计划（一级大纲）

        // 5-1 查询对应的一级大纲 select * from tb_teachplan where course_id = 47 and grade =1
        Teachplan oneTeachplan = teachplanService.lambdaQuery()
                .eq(Teachplan::getCourseId, newCourseBase.getId())
                .eq(Teachplan::getGrade, 1).one();
        // 5-2 修改名称和介绍
        oneTeachplan.setPname(newCourseBase.getName());
        oneTeachplan.setDescription(newCourseBase.getDescription());
        // 5-3 更新数据库
        teachplanService.updateById(oneTeachplan);
        // 6.返回课程id
        Map map = new HashMap();
        map.put("courseBaseId", oldCourseBase.getId());
        return ResponseResult.okResult(map);
    }


    @Autowired
    private MinioTemplate minioTemplate;
    // 课程删除
    @Override
    @Transactional
    public ResponseResult deleteCourseBase(Long courseId) {
        // 1.校验课程状态
        // 1-1 根据id查询课程
        CourseBase courseBase = this.getById(courseId);
        // 1-2 判断是否已发布
        if (StrUtil.equals(CourseConstants.AUDIT_PUBLISHED_STATUS,courseBase.getAuditStatus())) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        // 2.删除课程
        boolean isSuccess = this.removeById(courseId);
        if (isSuccess==false) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        //删除图片
        String pic = courseBase.getPic();
        String name = pic.substring(37);
        minioTemplate.removeObject(name);
        // 该课程下有 1 2 3级不允许删除
        Long count = teachplanService.lambdaQuery()
                .eq(Teachplan::getCourseId, courseId).count();
        if (count > 1) { // 有二级或者三级
            throw new BusinessException(ErrorCode.DELETEERROR);
        }

        // 只有1级的是可以删除的
        LambdaQueryWrapper<Teachplan> qw = new LambdaQueryWrapper<>();
        qw.eq(Teachplan::getCourseId, courseId);
        teachplanService.remove(qw);


        // 3.返回删除成功  状态码：200
        return ResponseResult.okResult();
    }

}













